//
//  AppController.m
//  Command-Q
//
//  Created by Timo Hetzel on 12.08.08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"


@implementation AppController
- (void)awakeFromNib;
{
	if(AXAPIEnabled())
	{
		NSRunAlertPanel(@"Alright.",@"\"Access for assistive devices\" was already enabled in System Preferences. Disable it to try trusting the application.", @"Quit", nil, nil);
		[NSApp terminate:nil];
	}
	else if(AXIsProcessTrusted())
	{
		NSRunAlertPanel(@"Yay!",@"We became trusted to use the Accessibility API.", @"Quit", nil, nil);
		[NSApp terminate:nil];
	}
	else
	{
		NSRunAlertPanel(@"Oh Noz!!",@"Access for assistive devices is not enabled and we are not trusted.", @"Make Process Trusted", nil, nil);
		[self makeProcessTrusted];
	}
}

- (void)makeProcessTrusted;
{
	//authentication based on file:///Developer/Documentation/DocSets/com.apple.ADC_Reference_Library.CoreReference.docset/Contents/Resources/Documents/documentation/Security/Conceptual/authorization_concepts/03authtasks/chapter_3_section_4.html
	
	OSStatus myStatus;
    AuthorizationFlags myFlags = kAuthorizationFlagDefaults;
    AuthorizationRef myAuthorizationRef;
	
    myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, myFlags, &myAuthorizationRef);
	
    if (myStatus != errAuthorizationSuccess)
	{
		[self askUserToEnableAccessForAssistiveDevices];
		return;
	}
	
	AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
	AuthorizationRights myRights = {1, &myItems};
	
	myFlags = kAuthorizationFlagDefaults |
	kAuthorizationFlagInteractionAllowed |
	kAuthorizationFlagPreAuthorize |
	kAuthorizationFlagExtendRights;
	myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights, NULL, myFlags, NULL );
	
	if (myStatus != errAuthorizationSuccess)
	{
		AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);
		[self askUserToEnableAccessForAssistiveDevices];
		return;
	}
	
	//we pass the path to our bundle to the agent so it can relaunch us when it makes us trusted
	char *myArguments[] = { (char *)([[[NSBundle mainBundle]bundlePath]fileSystemRepresentation]), NULL };
	
	const char *makeProcessTrustedAgentPath = [[[NSBundle bundleWithPath:[[NSBundle mainBundle]pathForAuxiliaryExecutable:@"MakeProcessTrustedAgent.app"]]executablePath]fileSystemRepresentation];
	
	
	//NSLog( makeProcessTrustedAgentPath);
	myFlags = kAuthorizationFlagDefaults;
	myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef,makeProcessTrustedAgentPath,myFlags,myArguments, NULL);
	
    AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);
	
    if (myStatus!= errAuthorizationSuccess)
	{
		[self askUserToEnableAccessForAssistiveDevices];
		return;
	}
	
	//due to a bug with AXMakeProcessTrusted(), we need to be relaunched before we will actually have access to UI Scripting
	[NSApp terminate:nil];
}
- (void)askUserToEnableAccessForAssistiveDevices;
{
	//fallback: ask the user to enable access for assistive devices manually
	int result = NSRunAlertPanel(@"Enable Access for Assistive Devices." , @"To continue, please enable access for assistive devices in the Universal Access pane in System Preferences. Then, relaunch the application." , @"Open System Preferences", @"Quit", nil);
	
	if(result == NSAlertDefaultReturn)
	{
		[[NSWorkspace sharedWorkspace]openFile:@"/System/Library/PreferencePanes/UniversalAccessPref.prefPane"];
	}
	
	//nothing else we can do right now
	[NSApp terminate:nil];
}

@end
